package com.example.springboot;

import com.example.springboot.web.WebServer;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.Map;

/**
 * @author: huangjiazhen
 * @create: 2023/1/11 18:05
 * @description:
 **/
public class TestSpringApplicaiton1 {

    public static void run(Class clazz) {
        // 创建spring容器
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz);
        applicationContext.refresh();
        // 启动服务
        WebServer webServer = getWebServer(applicationContext);
        webServer.start();
    }

    private static WebServer getWebServer(ApplicationContext applicationContext) {
        Map<String, WebServer> webServers = applicationContext.getBeansOfType(WebServer.class);
        if (webServers.isEmpty()) {
            throw new NullPointerException("没有webserver可用！");
        }
        if (webServers.size() > 1) {
            throw new IllegalArgumentException("配置的webServer数量大于1");
        }
        return webServers.values().stream().findFirst().get();
    }
}
